const http = require('http');

// .jpg  .jpeg  --->  image/jpeg
//.png  --->  image/png
//.gig --->  image/gif
//.ico  --->  image/x-ico
//.txt --->  text/plain
//.json  --->  text/json或application/json
//.xml ---> text/xml或application/xml

let html = `
<!DOCTYPE html>
<html>
    <head>
        <title>First HTTP</title>
    </head>
    <body>
        你好
    </body>
</html>
`
let routerTable = {
    '/':async(req,res) => {
        res.setHeader('content-type','text/html; charset=utf-8'); 
        res.end(html);
    },
    '/data':async(req,res) => {
        let bufferList = [];
        let bufferLength = 0;
        req.on('data',chunk => {
            bufferLength += chunk.length;
            bufferList.push(chunk);
        })

        let bodyData = null;
        req.on('end',() => {
            if(bufferList.length > 0){
            bodyData = Buffer.concat(bufferList,bufferLength);
            bufferList = [];
            }

            if(bodyData){
                res.end(bodyData);
            }else{
                res.end()
            }
        })
    },
    '/test':async(req,res) => {
        let status = parseInt(Math.random() * 200) + 199;
        res.statusCode = status;
        res.end('test end');
    }

}

http.createServer((req,res) => {
    if(!routerTable[req.url]){
        res.statusCode= 404;
        res.end('page not found');
        return
    }

    routerTable[req.url](req,res);
    
}).listen(3456)



